import React, { Component } from 'react';
import Title from '../Title'
import './index.scss'
import { getTabCar } from '../../api'
class Index extends Component {
  state = {
    activeIndex: 0,
    tabCar: [],
    totalPrice: 0
  }
  handleChangeIndex = (i) => {
    this.setState({
      activeIndex: i
    })
  }
  handleItem = (id, flag = true) => {
    const { activeIndex, tabCar } = this.state
    const item = tabCar[activeIndex].children.find(item => item.id === id)
    
    if(flag) {
      item.count++
    } else {
      item.count--
    }
  
    this.setState({
      tabCar: [...tabCar]
    })
  }
  async getTabCarAndSet() {
    const resp = await getTabCar()
    
    const { data } = resp.data

    this.setState({
      tabCar: data
    })
  }
  handleTotalPrice = () => {
    const { tabCar } = this.state
    let price = 0
    tabCar.forEach(v => v.children.forEach(v => {
      price += v.price * v.count
    }))

    this.setState({
      totalPrice: price
    })
  }
  componentDidMount() {
    this.getTabCarAndSet()
  }
  render() {
    const { activeIndex, tabCar, totalPrice } = this.state
    return (
      <div>
         <div className="tab">
        <Title list={tabCar} activeIndex={activeIndex} handleChangeIndex={this.handleChangeIndex}></Title>
        <div className="right">
          {
            tabCar.length > 0 && tabCar[activeIndex].children.map(item => {
              return (
                <dl key={item.id}>
                  <dt>
                    <img src={item.url} alt="" />
                  </dt>
                  <dt>
                    <h3>{item.title}</h3>
                    <p>{item.desc}</p>
                    <p>{item.price}</p>
                    <p>
                      {
                        item.count > 0 && (
                          <React.Fragment>
                            <button onClick={() => this.handleItem(item.id, false)}>-</button>
                            <b>{item.count}</b>
                          </React.Fragment>
                        )
                      }
                      <button onClick={() => this.handleItem(item.id)}>+</button>
                    </p>
                  </dt>
                </dl>
              )
            })
          }
        </div>
      </div>
      <div>
        总价： { totalPrice }
      </div>
      </div>
    );
  }
  componentDidUpdate(prevProps, prevState) {
    if(prevState.tabCar !== this.state.tabCar) {
      this.handleTotalPrice()
    }
  }
}

export default Index;
